package com.novix.portal.framework.service;

import javax.servlet.ServletException;

import org.apache.struts.action.ActionServlet;
import org.apache.struts.action.PlugIn;
import org.apache.struts.config.ModuleConfig;

import com.novix.portal.framework.exceptions.ApplicationException;
import com.novix.portal.framework.util.IConstants;

public class ServiceFactory implements IGenericServiceFactory, PlugIn {
    private ActionServlet servlet = null;

    String serviceClassname = "";

    public IGenericService createService() throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        String className = servlet.getInitParameter(IConstants.SERVICE_CLASS_KEY);
        if (className != null) {
            serviceClassname = className;
        } else
            throw new ApplicationException("No service impl has been specified in the web.xml...");
        IGenericService instance = (IGenericService) Class.forName(serviceClassname).newInstance();
        instance.setServletContext(servlet.getServletContext());
        return instance;
    }

    public void init(ActionServlet servlet, ModuleConfig config) throws ServletException {
        this.servlet = servlet;
        servlet.getServletContext().setAttribute(IConstants.SERVICE_FACTORY_KEY, this);
    }

    public void destroy() {
    }
}
